package com.sunday.gulimall.product.exception;

import com.sunday.common.exception.BizCodeEnume;
import com.sunday.common.utils.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @ClassName ControllerExceptionAdvice
 * @Description Controller异常处理类
 * @Author chuhao
 * @Date 2020/7/18 17:10
 * @Version 1.0
 */
@Log4j2
@RestControllerAdvice(basePackages = "com.sunday.gulimall.product.controller")
public class ControllerExceptionAdvice {

    // 参数建议异常处理
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validExceptionHandler(MethodArgumentNotValidException e) {
        log.error("数据校验异常");
        HashMap<Object, Object> resultMap = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((error) -> {
            resultMap.put(error.getField(), error.getDefaultMessage());
        });

        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", resultMap);
    }

    // 未知异常处理
    @ExceptionHandler(value = Throwable.class)
    public R commonExceptionHandler(Throwable e) {
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
